/* 
 * created by senllang 2024/1/1 
 * mail : study@senllang.onaliyun.com 
 *
 * Copyright (c) 2023-2024 senllang

 * This is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * 
 */

#include <stdio.h>  
#include <pthread.h>  
  
// 定义一个 TLS 键  
pthread_key_t tls_key;  

void ShowThreadLocalData(char *prompt, pthread_t thid)
{
    // 获取 TLS 存储的值  
    int *value = (int *) pthread_getspecific(tls_key);  
    if (value == NULL) 
    {  
        printf("[%s]Thread: %ld, Value: NULL\n", prompt, thid);  
    } else 
    {  
        printf("[%s]Thread: %ld, Value: %d\n", prompt, thid, *value);  
    }  
}

// 线程函数  
void *thread_func(void *arg) 
{  
    ShowThreadLocalData("pre", pthread_self());

    pthread_setspecific(tls_key, (void *) arg);

    ShowThreadLocalData("after", pthread_self());
    return NULL;  
}  
  
int main() 
{  
    // 创建 2 个线程  
    pthread_t thread1, thread2;  
    int args1 = 100, args2=200;

    pthread_key_create(&tls_key, NULL); 

    // 设置 TLS 值  
    pthread_setspecific(tls_key, (void *) 500);  

    pthread_create(&thread1, NULL, thread_func, &args1);  
    pthread_create(&thread2, NULL, thread_func, &args2);  
  
    // 等待线程结束  
    pthread_join(thread1, NULL);  
    pthread_join(thread2, NULL);  

    pthread_key_delete(tls_key);
    return 0;  
}